package com.css.zfzx.sjcj.modules.qhstandardpenetration.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.BeanUtil;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.QhDrillOverviewRepository;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.entity.QhDrillOverviewEntity;
import com.css.zfzx.sjcj.modules.qhsoildynamic.repository.entity.QhSoilDynamicEntity;
import com.css.zfzx.sjcj.modules.qhstandardpenetration.repository.QhStandardPenetrationNativeRepository;
import com.css.zfzx.sjcj.modules.qhstandardpenetration.repository.QhStandardPenetrationRepository;
import com.css.zfzx.sjcj.modules.qhstandardpenetration.repository.entity.QhStandardPenetrationEntity;
import com.css.zfzx.sjcj.modules.qhstandardpenetration.service.QhStandardPenetrationService;
import com.css.zfzx.sjcj.modules.qhstandardpenetration.viewobjects.QhStandardPenetrationQueryParams;
import com.css.zfzx.sjcj.modules.qhstandardpenetration.viewobjects.QhStandardPenetrationVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author aa
 * @date 2020-11-12
 */
@Slf4j
@Service
public class QhStandardPenetrationServiceImpl implements QhStandardPenetrationService {

	@Autowired
    private QhStandardPenetrationRepository qhStandardPenetrationRepository;
    @Autowired
    private QhStandardPenetrationNativeRepository qhStandardPenetrationNativeRepository;
    @Autowired
    private QhDrillOverviewRepository qhDrillOverviewRepository;

    @Override
    public JSONObject queryQhStandardPenetrations(QhStandardPenetrationQueryParams queryParams, int curPage, int pageSize) {
        Page<QhStandardPenetrationEntity> qhStandardPenetrationPage = this.qhStandardPenetrationNativeRepository.queryQhStandardPenetrations(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(qhStandardPenetrationPage);
        return jsonObject;
    }


    @Override
    public QhStandardPenetrationEntity getQhStandardPenetration(String id) {
        QhStandardPenetrationEntity qhStandardPenetration = this.qhStandardPenetrationRepository.findById(id).orElse(null);
         return qhStandardPenetration;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhStandardPenetrationEntity saveQhStandardPenetration(QhStandardPenetrationEntity qhStandardPenetration) {
        String uuid = UUIDGenerator.getUUID();
        qhStandardPenetration.setId(uuid);
        qhStandardPenetration.setCreateUser(PlatformSessionUtils.getUserId());
        qhStandardPenetration.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        qhStandardPenetration.setIsValid("1");
        qhStandardPenetration.setReviewStatus("0");
        qhStandardPenetration.setQualityinspectionStatus("0");
        this.qhStandardPenetrationRepository.save(qhStandardPenetration);
        return qhStandardPenetration;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhStandardPenetrationEntity updateQhStandardPenetration(QhStandardPenetrationEntity qhStandardPenetration) {
        qhStandardPenetration.setUpdateUser(PlatformSessionUtils.getUserId());
        qhStandardPenetration.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = qhStandardPenetration.getId();
        QhStandardPenetrationEntity one = qhStandardPenetrationRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(qhStandardPenetration, one);
        this.qhStandardPenetrationRepository.save(one);
        return qhStandardPenetration;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQhStandardPenetrations(List<String> ids) {
        List<QhStandardPenetrationEntity> qhStandardPenetrationList = this.qhStandardPenetrationRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(qhStandardPenetrationList) && qhStandardPenetrationList.size() > 0) {
            for(QhStandardPenetrationEntity qhStandardPenetration : qhStandardPenetrationList) {
//                this.qhStandardPenetrationRepository.delete(qhStandardPenetration);
                qhStandardPenetration.setUpdateUser(PlatformSessionUtils.getUserId());
                qhStandardPenetration.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhStandardPenetration.setIsValid("0");
                this.qhStandardPenetrationRepository.save(qhStandardPenetration);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitQhStandardPenetrations(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhStandardPenetrationEntity> qhDrillOverviewList = this.qhStandardPenetrationRepository.findAllById(idList);
        if(!PlatformObjectUtils.isEmpty(qhDrillOverviewList) && qhDrillOverviewList.size() > 0) {
            for(QhStandardPenetrationEntity qhDrillOverview : qhDrillOverviewList) {
                qhDrillOverview.setUpdateUser(PlatformSessionUtils.getUserId());
                qhDrillOverview.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhDrillOverview.setReviewStatus("1");
                this.qhStandardPenetrationRepository.save(qhDrillOverview);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            params.setTitleRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<QhStandardPenetrationVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), QhStandardPenetrationVO.class, params);
            List<QhStandardPenetrationVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<QhStandardPenetrationVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    QhStandardPenetrationVO areaVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + areaVO.getRowNum() + "行" + areaVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public String exportExcel(String ids, HttpServletResponse response) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhStandardPenetrationEntity> areaEntities = qhStandardPenetrationRepository.findAllById(idList);

        return exportExcel(areaEntities,response);
    }

    @Override
    public String exportExcel(List<QhStandardPenetrationEntity> areaEntities, HttpServletResponse response) {
        try {
            // 深拷贝
            ArrayList<QhStandardPenetrationVO> vos = new ArrayList<>();
            for (QhStandardPenetrationEntity areaEntity : areaEntities) {
                QhStandardPenetrationVO vo = new QhStandardPenetrationVO();
                BeanUtils.copyProperties(areaEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "钻孔标准贯入原位测试结果统计", "钻孔标准贯入原位测试结果", QhStandardPenetrationVO.class, "钻孔标准贯入原位测试结果.xls", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private void saveExcel(List<QhStandardPenetrationVO> list) {
        for (int i = 0; i < list.size(); i++) {
//            QhStandardPenetrationEntity areaEntity = new QhStandardPenetrationEntity();
            QhStandardPenetrationVO areaVO = list.get(i);
            QhStandardPenetrationEntity areaEntity = qhStandardPenetrationRepository.findById(areaVO.getId()).get();
            // 将VO数据映射拷贝到库表中
            BeanUtil.copyPropertiesIgnoreNull(areaVO, areaEntity);
            updateQhStandardPenetration(areaEntity);
        }
    }

    private void setCheckFields(Map<String,String> fields){
        fields.put("projectName","勘察工程名称");
        fields.put("drillCode","钻孔编号");
        fields.put("serialNumber","序号");
        fields.put("geotechnicalType","岩土类型");
        fields.put("standardStartDepth","标准贯入起始深度");
        fields.put("standardEndDepth","标准贯入结束深度");
        fields.put("standardHammerNumber","标准贯入锤击数");
        fields.put("standardMeasuredValue","标准贯入实验实测值");
        fields.put("province","省");
        fields.put("city","市");
        fields.put("area","区/县");
    }

    @Override
    public JSONObject dataQualityCheck(List<QhStandardPenetrationEntity> qhStandardPenetrationList){
        JSONObject res = new JSONObject();

        try {
            if(PlatformObjectUtils.isEmpty(qhStandardPenetrationList) || qhStandardPenetrationList.size() < 1) {
                return res;
            }

            Map<String, QhDrillOverviewEntity> drillCodeEntityMap = new HashMap<>();

            for(QhStandardPenetrationEntity qhStandardPenetration : qhStandardPenetrationList){
                //检查字段值不为空
                StringBuilder errorMsg = new StringBuilder();
                Map<String, String> methods = new HashMap<>();
                setCheckFields(methods);

                ServerUtil.checkFieldNull(qhStandardPenetration, methods, errorMsg);

                //检查标准贯入起始深度 标准贯入起始深度
                QhDrillOverviewEntity qhDrillOverviewEntity = null;
                String drillCode = qhStandardPenetration.getDrillCode();
                if(drillCodeEntityMap.containsKey(drillCode)){
                    qhDrillOverviewEntity = drillCodeEntityMap.get(drillCode);
                } else {
                    List<QhDrillOverviewEntity> qhDrillOverviewEntityList = this.qhDrillOverviewRepository.findByIsValidAndDrillCode("1",drillCode);
                    if(qhDrillOverviewEntityList.size() == 1){
                        qhDrillOverviewEntity = qhDrillOverviewEntityList.get(0);
                    }
                }
                if(qhDrillOverviewEntity != null){
                    float drillDepth = Float.parseFloat(qhDrillOverviewEntity.getDrillDepth());
                    float standardStartDepth = Float.parseFloat(qhStandardPenetration.getStandardStartDepth());
                    float standardEndDepth = Float.parseFloat(qhStandardPenetration.getStandardEndDepth());

                    if(standardStartDepth > drillDepth){
                        ServerUtil.addErrorMsg(errorMsg,"标准贯入起始深度","深度不超过终孔深度");
                    }
                    if(standardEndDepth > drillDepth){
                        ServerUtil.addErrorMsg(errorMsg,"标准贯入起始深度","深度不超过终孔深度");
                    }
                }

                //写入系统质检原因
                String strErrorMsg = errorMsg.toString();
                if(!strErrorMsg.isEmpty()) {
                    qhStandardPenetration.setQualityinspectionComments(strErrorMsg);
                    qhStandardPenetration.setQualityinspectionStatus("1");
                    qhStandardPenetration.setQualityinspectionResult("0");
                    this.updateQhStandardPenetration(qhStandardPenetration);

                    res.put(qhStandardPenetration.getId(),strErrorMsg);
                } else {
                    qhStandardPenetration.setQualityinspectionStatus("1");
                    qhStandardPenetration.setQualityinspectionResult("1");
                    this.updateQhStandardPenetration(qhStandardPenetration);
                }
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return res;
    }

    @Override
    public JSONObject dataQualityCheck(String drillCodes){
        List<String> idList = Arrays.asList(drillCodes.split(","));
        List<QhStandardPenetrationEntity> qhStandardPenetrationList = this.qhStandardPenetrationRepository.findByIsValidAndDrillCodeIn("1",idList);

        return dataQualityCheck(qhStandardPenetrationList);
    }
}
